package com.xc.stock.utils;

import java.util.function.Consumer;

import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

/**
 * 
 * title: TranUtils.java 
 *
 * @author xlfd
 * @email xlfd@gmail.com
 * @version 1.0  
 * @created Aug 27, 2020 2:40:02 PM
 */
public class ExTrans {
	static JpaTransactionManager transactionManager;
	static ExTrans tranUtils;
	
	public static ExTrans of() {
		if(tranUtils == null) {
			tranUtils = new ExTrans();
		}
		
		return tranUtils;
	}
	
	JpaTransactionManager getJpaTransactionManager() {
		if(transactionManager == null) {
			transactionManager = SpringUtils.getBean("transactionManager");
		}
		return transactionManager;
	}
	
	public TransactionStatus requiresNew() {
		DefaultTransactionDefinition def = new DefaultTransactionDefinition();
	    def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); 
	    TransactionStatus status = getJpaTransactionManager().getTransaction(def);
	    return status;
	}
	
	public void commit(TransactionStatus status) {
		if(! status.isCompleted()) {
			getJpaTransactionManager().commit(status);
		}
	}
	
	public void rollback(TransactionStatus status) {
		if(! status.isCompleted()) {
			getJpaTransactionManager().rollback(status);
		}
	}
	
	public void exec(Consumer<TransactionStatus> c) {
		TransactionStatus status = requiresNew();
		try {
			c.accept(status);
			commit(status);
		} catch(Exception e) {
			rollback(status);
			throw e;
		}
	}
}
